package workers;

import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;

import model.Software;
import workerUIs.StepFrame;
import workflow.IEventListener;
import workflow.WorkflowEvent;
import workflow.WorkflowEvent.EventType;
import workflow.step.IntegrationStep;

public class IntegrationStepWorker extends AbstractStepSwingWorker {

	private final BlockingQueue<Software> inputUIQueue;

	public IntegrationStepWorker(final StepFrame frame,
			final BlockingQueue<Software> inputImplQueue, final BlockingQueue<Software> inputUIQueue, final BlockingQueue<Software> outputTest, final StepFrame nextFrame, final IEventListener listener) {
		super(frame, inputImplQueue, outputTest, nextFrame, listener);
		this.inputUIQueue = inputUIQueue;
	}
	
	@Override
	protected String getTaskName() {
		return "integr";
	}

	@Override
	protected Software doInBackground() throws Exception {
		try {
			this.software = this.inputQueue.take();
			this.software = this.inputUIQueue.take();
			if (listener != null) listener.onEvent(WorkflowEvent.createEvent(this.software.getId(), getTaskName(), EventType.START));
			if (delay > 0L) {
				Thread.sleep(delay);
			}
			doStep(software);
			this.outputQueue.put(this.software);
			if (listener != null) listener.onEvent(WorkflowEvent.createEvent(this.software.getId(), getTaskName(), EventType.END));
			return this.software;
		} catch (Exception e) {
			logger.log(Level.SEVERE, "Exception when executing step: " + getClass().getName() + ": " + e.getMessage());
		}
		return null;
	}
	
	@Override
	protected void done() {
		if (inputQueue.isEmpty() && !inputUIQueue.isEmpty()) {
			getFrame().getNextButton().setEnabled(true);
		}
		super.done();
	}
	
	@Override
	protected Software doStep(Software software) {
		return new IntegrationStep().doStep(software);
	}

}
